<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;

class Clean extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('clean')
            ->addOption('path', 'd', Option::VALUE_OPTIONAL, 'path to clean')
            ->addOption('app', 'a', Option::VALUE_OPTIONAL, 'app name')
            ->addOption('cache', 'c', Option::VALUE_NONE, 'clean cache file')
            ->addOption('log', 'l', Option::VALUE_NONE, 'clean log file')
            ->addOption('dir', 'r', Option::VALUE_NONE, 'clean empty dir')
            ->addOption('expire', 'e', Option::VALUE_NONE, 'clean cache file if cache has expired')
            ->setDescription('Clean runtime file（多应用模式）');
    }

    protected function execute(Input $input, Output $output)
    {
        $path = $input->getOption('path');
        if (empty($path)) {
            $path = root_path() . 'runtime';
            if ($app = $input->getOption('app')) {
                $path .= DIRECTORY_SEPARATOR . $app;
            }
            if ($input->getOption('cache')) {
                $path .= DIRECTORY_SEPARATOR . 'cache';
            } elseif ($input->getOption('log')) {
                $path .= DIRECTORY_SEPARATOR . 'log';
            }
        }

        $rmdir = $input->getOption('dir') ? true : false;

        // --expire 仅当 --cache 时生效
        $cache_expire = $input->getOption('expire') && $input->getOption('cache') ? true : false;

        $this->clean($path, $rmdir, $cache_expire);

        $output->writeln("<info>Clean Successed</info>");
    }

    protected function clean(string $path, bool $rmdir, bool $cache_expire): void
    {
        $path = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;
        $files = is_dir($path) ? scandir($path) : [];

        foreach ($files as $file) {
            if ('.' != $file && '..' != $file && is_dir($path . $file)) {
                $this->clean($path . $file, $rmdir, $cache_expire);
                if ($rmdir) {
                    @rmdir($path . $file);
                }
            } elseif ('.gitignore' != $file && is_file($path . $file)) {
                if ($cache_expire) {
                    if ($this->cacheHasExpired($path . $file)) {
                        unlink($path . $file);
                    }
                } else {
                    unlink($path . $file);
                }
            }
        }
    }

    /**
     * 缓存文件是否已过期
     * @param $filename string 文件路径
     * @return bool
     */
    protected function cacheHasExpired($filename)
    {
        $content = file_get_contents($filename);
        $expire = (int) substr($content, 8, 12);
        return 0 != $expire && time() - $expire > filemtime($filename);
    }
}
